package com.ruoyi.zsyh.controller.applet.store;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 服务订单 -- 第一版个人订单
 */
@Controller
@RequestMapping("/applet/zsyh/storeServiceOrder")
public class ZsyhStoreServiceOrderAppletController extends BaseController
{

    @Autowired
    private IZsyhServiceTypeService zsyhServiceTypeService;

    @Autowired
    private IZsyhUserAddressService zsyhUserAddressService;

    @Autowired
    private IZsyhServiceOrderService zsyhServiceOrderService;

    @Autowired
    private IZsyhServiceOrderLogService zsyhServiceOrderLogService;

    @Autowired
    private IZsyhUserRepairstoreService zsyhUserRepairstoreService;

    @Autowired
    private IZsyhServiceSettleService zsyhServiceSettleService;

    @Autowired
    private IZsyhServiceOrderCommissionService zsyhServiceOrderCommissionService;

    @Autowired
    private IZsyhServiceOrderPartsService zsyhServiceOrderPartsService;

    /**
     * 我的店铺 服务订单数量
     * @return
     */
    @RequestMapping("/getStoreServiceOrderNumByUserId")
    @ResponseBody
    public AjaxResult getStoreServiceOrderNumByUserId(String userId)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();

        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setRepairStoreId(repairId);
        order.setOrderState("0");
        List<ZsyhServiceOrder> orderList1 = zsyhServiceOrderService.selectZsyhServiceOrderList(order);//店铺未接订单

        order = new ZsyhServiceOrder();
        order.setOrderState("0");
        Map map = new HashedMap();
        map.put("repairId", "空");
        order.setParams(map);
        List<ZsyhServiceOrder> orderList2 = zsyhServiceOrderService.selectZsyhServiceOrderList(order);//平台未接订单
        map = new HashedMap();
        map.put("repairOrderNum", orderList1.size());
        map.put("orderNum", orderList2.size());
        return success("成功", map);
    }

    /**
     * 维修师傅接单判断是否有未缴费订单
     * @return
     */
    @RequestMapping("/getStoreServiceOrderUnpaidNumByUserId")
    @ResponseBody
    public AjaxResult getStoreServiceOrderUnpaidNumByUserId(String userId)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();

        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setRepairStoreId(repairId);
        order.setOrderFixdrawState("0");
        Map map = new HashedMap();
        map.put("orderState", "未缴费");
        order.setParams(map);
        List<ZsyhServiceOrder> orderList = zsyhServiceOrderService.selectZsyhServiceOrderList(order);//店铺未接订单
        map = new HashedMap();
        map.put("orderUnpaidNum", orderList.size());
        String orderId = "";
        if(orderList.size() > 0){
            orderId = orderList.get(0).getId();
        }
        map.put("orderId", orderId);
        return success("成功", map);
    }


    /**
     * 获取服务订单列表
     * @return
     */
    @RequestMapping("/getStoreServiceOrderListByUserId")
    @ResponseBody
    public AjaxResult getStoreServiceOrderListByUserId(String userId, String orderType, String orderState, String pageNum, String pageSize)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();

        ZsyhServiceOrder order = new ZsyhServiceOrder();
        if(EmptyUtils.isNotEmpty(orderState)){
            order.setOrderState(orderState);
        }
        order.setOrderType(orderType);
        if("2".equals(orderType)){
            order.setRepairStoreId(repairId);
        }


        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        map.put("orderState", "未取消");
        map.put("repairStoreId", repairId);
        order.setParams(map);
        List<ZsyhServiceOrder> orderList = zsyhServiceOrderService.selectZsyhServiceOrderList(order);
        return success("成功", orderList);
    }

    /**
     * 接单  维修师傅接单
     * @return
     * @throws Exception
     */
    @RequestMapping("/receiveServiceOrder")
    @ResponseBody
        public AjaxResult receiveServiceOrder(String orderId, String userId)throws Exception
    {
        ZsyhServiceOrder order1 = zsyhServiceOrderService.selectZsyhServiceOrderById(orderId);
        String orderUserId = order1.getUserId();
        if(userId.equals(orderUserId)){
            return error("请勿接自己下的订单");
        }

        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();
//        String orderType = order1.getOrderType();//订单分类 1个人订单 2厂家售后单 3保外订单 4厂家售后返修单

        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setId(orderId);
        order.setRepairStoreId(repairId);
        //订单状态 001厂家保存（未下单） 0未接单（厂家下单）1已接单 101已预约 102服务中  201平台待审核 202厂家待审核 2已完成 203待拨款 3已支付 4已评价 5已取消 501师傅申请取消 6系统自动取消
//        if("1".equals(orderType)){
//            order.setOrderState("102");
//        }else{
        order.setOrderState("1");
//        }
        order.setReceiptTime(new Date());
        zsyhServiceOrderService.updateZsyhServiceOrder(order);

        ZsyhServiceOrderParts parts = new ZsyhServiceOrderParts();
        parts.setOrderId(orderId);
        List<ZsyhServiceOrderParts> partsList = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(parts);
        for(ZsyhServiceOrderParts a:partsList){
            ZsyhServiceOrderParts parts1 = new ZsyhServiceOrderParts();
            parts1.setId(a.getId());
            parts1.setRepairId(repairId);
            parts1.setUserName(order1.getUserName());
            parts1.setUserPhone(order1.getUserPhone());
            parts1.setUserAddress(order1.getUserAddress());
            parts1.setFaultDescription("厂家已发配件");
            parts1.setIsNewParts("1");
            zsyhServiceOrderPartsService.updateZsyhServiceOrderParts(parts1);
        }

        ZsyhServiceOrderLog log = new ZsyhServiceOrderLog();
        log.setId(IdWorker.getId());
        log.setOrderId(orderId);
        log.setLogType("1");
        log.setLogContent("师傅接单");
        zsyhServiceOrderLogService.insertZsyhServiceOrderLog(log);

        return success("成功");
    }

    /**
     * 生成电子保单
     * @param orderId
     * @return
     * @throws Exception
     */
    @RequestMapping("/generateElectronicPolicy")
    @ResponseBody
    public AjaxResult generateElectronicPolicy(String orderId, String warrantyDate, String repairTime, String repairContent, String repairParts)throws Exception
    {
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setId(orderId);
        order.setOrderState("2");
        order.setWarrantyDate(warrantyDate);
        order.setRepairTime(repairTime);
        order.setRepairContent(repairContent);
        order.setRepairParts(repairParts);
        zsyhServiceOrderService.updateZsyhServiceOrder(order);
        return success("成功");
    }


    /**
     * 市县 个人中心 收益看板
     * @param userId
     * @return
     */
    @RequestMapping("/getServiceSettleByRakerId")
    @ResponseBody
    public AjaxResult getServiceSettleByRakerId(String userId)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);


        if(store == null){
            return error("您不是市县管理商");
        }
        Double rakerCommission = 0.00;//今日收益
        Double rakerCommissionNow = 0.00;//当前收益
        String rakerCommissionAll = "0";//累计总收益
        String rakerId = store.getId();//市县id

        String endDate = DateUtils.getDate();
        String startDate = endDate;
        if(EmptyUtils.isNotEmpty(startDate) && EmptyUtils.isNotEmpty(endDate)){
            startDate += " 00:00:00";
            endDate += " 23:59:59";
        }
        Map map = new HashedMap();
        ZsyhServiceOrderCommission commission = new ZsyhServiceOrderCommission();
        commission.setRakerId(rakerId);
        map.put("beginCreateTime", startDate);
        map.put("endCreateTime", endDate);
        commission.setParams(map);

        List<ZsyhServiceOrderCommission> commissionList = zsyhServiceOrderCommissionService.selectZsyhServiceOrderCommissionList(commission);
        for (ZsyhServiceOrderCommission a:commissionList){
            rakerCommission += a.getRakerCommission().doubleValue();
        }



        ZsyhServiceSettle zsyhServiceSettle = new ZsyhServiceSettle();
        zsyhServiceSettle.setRakerId(rakerId);
        zsyhServiceSettle.setSettleStatue("1");
        List<ZsyhServiceSettle> list = zsyhServiceSettleService.selectZsyhServiceSettleList(zsyhServiceSettle);

        if(list.size() > 0){
            for(ZsyhServiceSettle a:list){
                rakerCommissionNow += a.getRakerSettleMoney().doubleValue();
            }
        }
        Map allMoneyMap = zsyhServiceSettleService.getMoneyAll(null, rakerId, null);
        if(allMoneyMap != null){
            rakerCommissionAll = String.valueOf(allMoneyMap.get("settleMoney"));
        }

        map = new HashedMap();
        map.put("rakerCommission", new BigDecimal(String.valueOf(rakerCommission)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        map.put("rakerCommissionNow", new BigDecimal(String.valueOf(rakerCommissionNow)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        map.put("rakerCommissionAll", rakerCommissionAll);
        return success("成功", map);
    }

    /**
     * 收益趋势图
     * @param userId
     * @param type 1本周 2本月 3 3个月 4 6个月
     * @return
     * @throws Exception
     */
    @RequestMapping("/getCommisionByRakerId")
    @ResponseBody
    public AjaxResult getCommisionByRakerId(String userId, String type)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);

        if(store == null){
            return error("您不是市县管理商");
        }
        String rakerId = store.getId();

        String endDate = DateUtils.getDate();
        String startDate = "";
        switch (type){
            case "1": startDate = DateUtils.getWeekStart();break;
            case "2": startDate = DateUtils.getMonthFirstDay();break;
            case "3": startDate = DateUtils.getLeftMonth(-3);break;
            case "4": startDate = DateUtils.getLeftMonth(-6);break;
        }
        if(EmptyUtils.isNotEmpty(startDate) && EmptyUtils.isNotEmpty(endDate)){
            startDate += " 00:00:00";
            endDate += " 23:59:59";
        }
        Map map = new HashedMap();
        ZsyhServiceOrderCommission commission = new ZsyhServiceOrderCommission();
        commission.setRakerId(rakerId);
        map.put("beginCreateTime", startDate);
        map.put("endCreateTime", endDate);
        commission.setParams(map);
        List<Map> commissionList = zsyhServiceOrderCommissionService.getCommisionByRakerId(commission);

        return success("成功", commissionList);
    }

    /**
     * 收益明细 当前收益
     * @param type 1今日 2本月 3 3个月 4 6个月
     * @return
     */
    @RequestMapping("/getServiceSettleDetails")
    @ResponseBody
    public AjaxResult getServiceSettleDetails(String userId, String areaId, String type)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);

        if(store == null){
            return error("您不是市县管理商");
        }
        String rakerId = store.getId();

        Double rakerCommission = 0.00;//当前收益
        ZsyhServiceSettle zsyhServiceSettle = new ZsyhServiceSettle();
        zsyhServiceSettle.setRakerId(rakerId);
        zsyhServiceSettle.setSettleStatue("1");
        List<ZsyhServiceSettle> list = zsyhServiceSettleService.selectZsyhServiceSettleList(zsyhServiceSettle);
        List<Map> dateList = new ArrayList<>();
        if(list.size() > 0){
            for(ZsyhServiceSettle a:list){
//                rakerCommissionNow += a.getRakerSettleMoney().doubleValue();
                Map map = new HashMap();
                map.put("y", a.getPeriodYear());
                map.put("m", a.getPeriodMonth());
                dateList.add(map);
            }

        }
//        Map allMoneyMap = zsyhServiceSettleService.getMoneyAll(null, rakerId, null);
//        if(allMoneyMap != null){
//            rakerCommissionAll = String.valueOf(allMoneyMap.get("settleMoney"));
//        }

        String endDate = DateUtils.getDate();
        String startDate = "";
        switch (type){
            case "1": startDate = endDate;break;
            case "2": startDate = DateUtils.getMonthFirstDay();break;
            case "3": startDate = DateUtils.getLeftMonth(-3);break;
            case "4": startDate = DateUtils.getLeftMonth(-6);break;
        }
        if(EmptyUtils.isNotEmpty(startDate) && EmptyUtils.isNotEmpty(endDate)){
            startDate += " 00:00:00";
            endDate += " 23:59:59";
        }
        Map map = new HashedMap();
        ZsyhServiceOrderCommission commission = new ZsyhServiceOrderCommission();
        commission.setOrderAreaId(areaId);
        commission.setRakerId(rakerId);
        map.put("beginCreateTime", startDate);
        map.put("endCreateTime", endDate);
        map.put("dateList", dateList);
        commission.setParams(map);
        List<ZsyhServiceOrderCommission> commissionList = zsyhServiceOrderCommissionService.selectZsyhServiceOrderCommissionList(commission);
        for(ZsyhServiceOrderCommission a:commissionList){
            rakerCommission += a.getRakerCommission().doubleValue();
        }



        map = new HashedMap();
        map.put("rakerCommission", new BigDecimal(String.valueOf(rakerCommission)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        map.put("commissionList", commissionList);
        return success("成功", map);
    }

    /**
     * 收益明细 累计收益
     * @param type 1今日 2本月 3 3个月 4 6个月
     * @return
     */
    @RequestMapping("/getServiceSettleDetailsAll")
    @ResponseBody
    public AjaxResult getServiceSettleDetailsAll(String userId, String areaId, String type)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);

        if(store == null){
            return error("您不是市县管理商");
        }
        String rakerId = store.getId();

        Double rakerCommission = 0.00;//累计收益

        String endDate = DateUtils.getDate();
        String startDate = "";
        switch (type){
            case "1": startDate = endDate;break;
            case "2": startDate = DateUtils.getMonthFirstDay();break;
            case "3": startDate = DateUtils.getLeftMonth(-3);break;
            case "4": startDate = DateUtils.getLeftMonth(-6);break;
        }
        if(EmptyUtils.isNotEmpty(startDate) && EmptyUtils.isNotEmpty(endDate)){
            startDate += " 00:00:00";
            endDate += " 23:59:59";
        }
        Map map = new HashedMap();
        ZsyhServiceOrderCommission commission = new ZsyhServiceOrderCommission();
        commission.setOrderAreaId(areaId);
        commission.setRakerId(rakerId);
        map.put("beginCreateTime", startDate);
        map.put("endCreateTime", endDate);
        commission.setParams(map);
        List<ZsyhServiceOrderCommission> commissionList = zsyhServiceOrderCommissionService.selectZsyhServiceOrderCommissionList(commission);
        for(ZsyhServiceOrderCommission a:commissionList){
            rakerCommission += a.getRakerCommission().doubleValue();
        }

        map = new HashedMap();
        map.put("rakerCommission", new BigDecimal(String.valueOf(rakerCommission)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        map.put("commissionList", commissionList);
        return success("成功", map);
    }

    /**
     * 历史结算 结算记录
     * @return
     * @throws Exception
     */
    @RequestMapping("/getServiceSettleHistoryByRakerId")
    @ResponseBody
    public AjaxResult getServiceSettleHistoryByRakerId(String userId)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);

        if(store == null){
            return error("您不是市县管理商");
        }
        ZsyhServiceSettle zsyhServiceSettle = new ZsyhServiceSettle();
        zsyhServiceSettle.setRakerId(store.getId());
        zsyhServiceSettle.setSettleStatue("2");
        String endDate = DateUtils.getDate();
        String startDate = DateUtils.getLeftYear(-1);
        if(EmptyUtils.isNotEmpty(startDate) && EmptyUtils.isNotEmpty(endDate)){
            startDate += " 00:00:00";
            endDate += " 23:59:59";
        }
        Map map = new HashedMap();
        map.put("beginCreateTime", startDate);
        map.put("endCreateTime", endDate);
        zsyhServiceSettle.setParams(map);
        List<ZsyhServiceSettle> list = zsyhServiceSettleService.selectZsyhServiceSettleList(zsyhServiceSettle);
        return success("成功", list);
    }

    /**
     * 获取服务订单列表
     * @return
     */
    @RequestMapping("/getStoreServiceOrderListByRakerId")
    @ResponseBody
    public AjaxResult getStoreServiceOrderListByRakerId(String userId, String pageNum, String pageSize)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);

        if(store == null){
            return error("您不是市县管理商");
        }

        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setRakerId(store.getId());
        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
//        map.put("orderState", "未取消");
        map.put("orderState", "未缴费");//未缴费 就是已结单，未取消的
        order.setParams(map);
        List<ZsyhServiceOrder> orderList = zsyhServiceOrderService.selectZsyhServiceOrderList(order);
        return success("成功", orderList);
    }


    /**
     * 获取超时未结单列表
     * @return
     */
    @RequestMapping("/getServiceOrderOverTimeListByRakerId")
    @ResponseBody
    public AjaxResult getServiceOrderOverTimeListByRakerId(String userId, String pageNum, String pageSize, String orderStateRaker)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);

        if(store == null){
            return error("您不是市县管理商");
        }

        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setRakerId(store.getId());
        order.setOrderState("0");
        order.setOrderStateRaker(orderStateRaker);
        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        map.put("overTime", "超时");
        order.setParams(map);
        List<ZsyhServiceOrder> orderList = zsyhServiceOrderService.selectZsyhServiceOrderList(order);
        return success("成功", orderList);
    }


    /**
     * 超时未结单 市县去处理
     * @param orderId
     * @return
     * @throws Exception
     */
    @RequestMapping("/handleServiceOrder")
    @ResponseBody
    public AjaxResult handleServiceOrder(String orderId)throws Exception
    {
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setId(orderId);
        order.setOrderStateRaker("1");
        zsyhServiceOrderService.updateZsyhServiceOrder(order);
        return success("成功");
    }

    /**
     * 超时未结单 市县处理完成
     * @param orderId
     * @return
     * @throws Exception
     */
    @RequestMapping("/handleCompleteServiceOrder")
    @ResponseBody
    public AjaxResult handleCompleteServiceOrder(String orderId, String processingResults)throws Exception
    {
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setId(orderId);
        order.setOrderStateRaker("2");
        order.setProcessingResults(processingResults);
        zsyhServiceOrderService.updateZsyhServiceOrder(order);
        return success("成功");
    }
}
